package com.eds.mall.product.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eds.common.dto.MemberPrice;
import com.eds.common.dto.SkuHasStockDto;
import com.eds.common.dto.SkuReductionDTO;
import com.eds.common.dto.SpuBoundsDTO;
import com.eds.common.dto.es.SkuESModel;
import com.eds.common.enumeration.PublishStatus;
import com.eds.common.exception.RRException;
import com.eds.common.utils.PageUtils;
import com.eds.common.utils.Query;
import com.eds.common.utils.R;
import com.eds.mall.product.entity.*;
import com.eds.mall.product.feign.CouponService;
import com.eds.mall.product.feign.SearchFeignService;
import com.eds.mall.product.feign.WareFeignService;
import com.eds.mall.product.service.*;
import com.eds.mall.product.vo.*;
import com.google.common.base.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.eds.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    AttrService attrService;

    @Autowired
    CouponService couponService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    BrandService brandService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SpuInfoDao spuInfoDao;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        // 关键字 key
        String keyParam = (String) params.get("key");
        if (!Strings.isNullOrEmpty(keyParam)) {
            wrapper.and(obj -> {
                obj.eq("id", keyParam)
                        .or().like("spu_name", keyParam)
                        .or().like("spu_description", keyParam);
            });
        }

        // 所属分类id catelogId
        wrapper.eq(!StringUtils.isEmpty(params.get("catalogId"))
                && !((String) params.get("catalogId")).equals("0"), "catalog_id", params.get("catalogId"));
        // 品牌 brandId
        wrapper.eq(!StringUtils.isEmpty(params.get("brandId"))
                && !((String) params.get("brandId")).equals("0"), "brand_id", params.get("brandId"));
        // 上架状态 status
        wrapper.eq(!StringUtils.isEmpty(params.get("status")), "publish_status", params.get("status"));

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), wrapper);

        // 根据查询到的分页信息，再查询出对应的类别名称和品牌名称
        List<SpuInfoVO> list = page.getRecords().stream().map(spu -> {
            Long catalogId1 = spu.getCatalogId();
            CategoryEntity categoryEntity = categoryService.getById(catalogId1);
            Long brandId1 = spu.getBrandId();
            BrandEntity brandEntity = brandService.getById(brandId1);
            SpuInfoVO vo = new SpuInfoVO();
            BeanUtils.copyProperties(spu, vo);
            vo.setCatalogName(categoryEntity.getName());
            vo.setBrandName(brandEntity.getName());
            return vo;
        }).collect(Collectors.toList());
        IPage<SpuInfoVO> iPage = new Page<SpuInfoVO>();
        iPage.setRecords(list);
        iPage.setPages(page.getPages());
        iPage.setCurrent(page.getCurrent());
        return new PageUtils(iPage);

    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuInfoVO spuInfoVo) {
        // 1.保存spu的基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVo, spuInfoEntity);
        // 创建时间和更新时间需要我们手动的来同步
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoEntity.setPublishStatus(PublishStatus.下架.getValue()); // 设置状态为新建状态
        this.save(spuInfoEntity);
        // 2.保存spu的详情信息 pms_spu_info_desc
        List<String> decripts = spuInfoVo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",", decripts));
        spuInfoDescService.save(descEntity);

        // 3.保存图集信息 pms_spu_images
        List<String> images = spuInfoVo.getImages();
        // 将每一个图片信息封装成一个SpuImagesEntity实体对象
        List<SpuImagesEntity> imagesEntities = images.stream().map(item -> {
            SpuImagesEntity entity = new SpuImagesEntity();
            entity.setSpuId(spuInfoEntity.getId());
            entity.setImgUrl(item);
            return entity;
        }).collect(Collectors.toList());
        spuImagesService.saveBatch(imagesEntities);

        // 4.保存规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfoVo.getBaseAttrs();
        // 对规格数据做对应的处理
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setSpuId(spuInfoEntity.getId()); // 关联商品编号
            valueEntity.setAttrId(attr.getAttrId());
            valueEntity.setAttrValue(attr.getAttrValues());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setQuickShow(attr.getShowDesc());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);
        // 5.保存当前的spu对应的所有的sku信息
        List<Skus> skus = spuInfoVo.getSkus();
        if (skus != null && skus.size() > 0) {
            // 5.1 保存sku的基本信息 pms_sku_info
            skus.forEach((item) -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                List<Images> images1 = item.getImages();
                String defaultImage = "";
                for (Images images2 : images1) {
                    if (images2.getDefaultImg() == 1) {
                        // 表示是默认的图片
                        defaultImage = images2.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoService.save(skuInfoEntity);
                // 5.2 保存sku的图片信息 pms_sku_image
                List<SkuImagesEntity> skuImagesEntities = images1.stream().map(img -> {
                    SkuImagesEntity entity = new SkuImagesEntity();
                    entity.setSkuId(skuInfoEntity.getSkuId());
                    entity.setImgUrl(img.getImgUrl());
                    entity.setDefaultImg(img.getDefaultImg());
                    return entity;
                }).filter(img -> {
                    return img.getDefaultImg() == 1;
                }).collect(Collectors.toList()); // TODO 为空的图片不需要保存
                skuImagesService.saveBatch(skuImagesEntities);
                // 5.3 保存满减信息，折扣，会员价 mall_sms: sms_sku_ladder sms_full_reduction sms_member_price
                SkuReductionDTO dto = new SkuReductionDTO();
                BeanUtils.copyProperties(item, dto);
                dto.setSkuId(skuInfoEntity.getSkuId());
                // 设置会员价
                if (item.getMemberPrice() != null && item.getMemberPrice().size() > 0) {
                    List<MemberPrice> list = item.getMemberPrice().stream().map(memberPrice -> {
                        MemberPrice mDto = new MemberPrice();
                        BeanUtils.copyProperties(memberPrice, mDto);
                        return mDto;
                    }).collect(Collectors.toList());
                    dto.setMemberPrice(list);
                }
                R r = couponService.saveFullReductionInfo(dto);
                if (r.getCode() != 0) {
                    log.error("调用Coupon服务处理满减、折扣，会员价操作失败...");
                }
                // 5.4 sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = attrs.stream().map(sale -> {
                    SkuSaleAttrValueEntity entity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(sale, entity);
                    entity.setSkuId(skuInfoEntity.getSkuId());
                    return entity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);
            });
        }
        // 6.保存spu的积分信息：mall-sms: sms_spu_bounds
        Bounds bounds = spuInfoVo.getBounds();
        SpuBoundsDTO spuBoundsDTO = new SpuBoundsDTO();
        BeanUtils.copyProperties(bounds, spuBoundsDTO);
        spuBoundsDTO.setSpuId(spuInfoEntity.getId());
        R r = couponService.saveSpuBounds(spuBoundsDTO);
        if (r.getCode() != 0) {
            log.error("调用Coupon服务存储积分信息操作失败");
        }

    }

    /**
     * 实现商品上架存储到 -> ElasticSearch
     * 1. 根据 spuid查询对应信息，存储到对应的对象中
     * 2. 调用mall-search接口，进行存储
     * 3. 更新spu状态
     *
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        // 1.根据 spuid查询对应信息，存储到对应的对象(SkuESModel)中
        //  1.1 根据spu获取产品的所有spu属性
        List<SkuESModel.Attrs> attrs = getAttrsModel(spuId);
        //  1.2 根据 spu获取sku
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpu(spuId);
        List<Long> skuIds = skus.stream().map(obj -> obj.getSkuId()).collect(Collectors.toList());
        // 1.3 获取查询是否有库存
        Map<Long, Boolean> hasStoreMap = mapSkuHasStore(skuIds);
        List<SkuESModel> esModels = skus.stream().map(obj -> {
            SkuESModel model = new SkuESModel();
            // 先处理相同的属性
            BeanUtils.copyProperties(obj, model);
            model.setSubTitle(obj.getSkuSubtitle());
            model.setSkuPrice(obj.getPrice());
            // 判断是否还有库存
            Boolean flag = hasStoreMap.get(obj.getSkuId());
            model.setHasStock(Objects.isNull(flag)? false : flag);
            // 初始的热度一定为0
            model.setHotScore(0l);
            // 品牌名称与类型名称
            BrandEntity brand = brandService.getById(model.getBrandId());
            model.setBrandName(brand.getName());
            CategoryEntity category = categoryService.getById(model.getCatalogId());
            model.setCatalogName(category.getName());
            // spu属性(spu属于同一属性)
            model.setAttrs(attrs);
            return model;
        }).collect(Collectors.toList());

        // 2. 调用 mall-es 服务，进行数据存储
        R r = searchFeignService.productStatusUp(esModels);
        if(r.getCode() != 0) {
            throw new RRException("商品上线异常, 清查对");
        }

        // 3. 修改spu上架状态
        spuInfoDao.modifySpuPublicStatus(spuId, PublishStatus.上架.getValue());
    }

    private Map<Long, Boolean> mapSkuHasStore(List<Long> skuIds) {
        // feign 调用ware
        List<SkuHasStockDto> data = wareFeignService.hasStock(skuIds);
        Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuHasStockDto::getSkuId, SkuHasStockDto::getHasStock));

        return map;
    }

    private List<SkuESModel.Attrs> getAttrsModel(Long spuId) {
        List<ProductAttrValueEntity> attrEntities = productAttrValueService.getSpuAttrBySpuId(spuId);
        // 查询能够检索的属性
        List<Long> attrIds = attrEntities.stream().map(obj -> obj.getAttrId()).collect(Collectors.toList());
        List<Long> canSearchAttrIds = attrService.listCanSearchAttr(attrIds);

        List<SkuESModel.Attrs> list = attrEntities.stream()
                .filter(obj -> canSearchAttrIds.contains(obj.getAttrId()) )
                .map(obj -> {
                    SkuESModel.Attrs attrs = new SkuESModel.Attrs();
                    attrs.setAttrId(obj.getId());
                    attrs.setAttrName(obj.getAttrName());
                    attrs.setAttrValue(obj.getAttrValue());
                    return attrs;
                }).collect(Collectors.toList());

        return list;
    }
}